<template>
  <div class="pagination">
    <button :disabled="pageNo === 1" @click="$emit('changePageNo', pageNo - 1)">
      上一页
    </button>
    <button v-if="startEnd.start > 1" @click="$emit('changePageNo', 1)">
      1
    </button>
    <button v-if="startEnd.start > 2">···</button>

    <button
      :class="{ active: pageNo === startEnd.start + num - 1 }"
      v-for="num in startEnd.end - startEnd.start + 1"
      :key="num"
      @click="$emit('changePageNo', startEnd.start + num - 1)"
    >
      {{ startEnd.start + num - 1 }}
    </button>

    <button v-if="startEnd.end < totalPage - 1">···</button>
    <button
      v-if="startEnd.end < totalPage"
      @click="$emit('changePageNo', totalPage)"
    >
      {{ totalPage }}
    </button>
    <button
      :disabled="pageNo === totalPage"
      @click="$emit('changePageNo', pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  // props:['total','pageNo','continues','pageSize']
  props: {
    total: Number,
    pageNo: {
      type: Number,
      default: 10, //默认值 不传值时生效
    },
    continues: {
      type: Number,
      required: true, //表示必须传递值
    },
    pageSize: Number,
  },
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize)
    },
    // 计算起始页和结束页
    startEnd() {
      let start
      let end
      let { pageNo, continues, totalPage } = this
      if (continues > totalPage) {
        //连续页大于总页数
        start = 1
        end = totalPage
      } else {
        //连续页小于总页数
        //正常情况
        start = pageNo - Math.floor(continues / 2)
        end = pageNo + Math.floor(continues / 2)
        if (start < 1) {
          //左侧超出 0 1 二 3 4  修改为 1 2 三 4 5
          start = 1
          end = continues
        }
        if (end > totalPage) {
          //右侧超出 7 8 九 10 11  修改为 6 7 8 九 10
          end = totalPage
          start = totalPage - continues + 1
        }
      }
      return {
        start,
        end,
      }
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
